<?php


namespace app\api\helpers\traits;

use app\api\model\Image;
use app\api\model\PlaceType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Env;

trait ImageUpload
{
    /**
     * @param $file    文件
     * @param $folder  文件夹名称
     * 上传图片
     * @return array
     */
    public function save($file, $folder)
    {
        $savename = \think\facade\Filesystem::disk('public')
            ->putFile($folder, $file);
        $path     = str_replace('\\', '/', $savename);
        return [
            'path' =>  $path,
        ];
    }


    //导入
    public function saveImportExcel($file, $folder)
    {
        $savename = \think\facade\Filesystem::disk('public')->putFile($folder, $file);
        $path = app()->getRootPath() . 'public/storage/'.str_replace('\\', '/', $savename);
        $returnData = $this->loadExcel($path);
        $data = $this->dadaFilter($returnData);
        return $data;
    }

    //创建文件夹
    public function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!mkdir(dirname($dir), $mode)) {
            return false;
        }
        return @mkdir($dir, $mode);
    }


    //载入excel
    public function loadExcel($filePath){
        $inputFileType = IOFactory::identify($filePath);
        $reader = IOFactory::createReader($inputFileType);
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($filePath); //载入excel表格
        $res_arr = array();
        $reader = $spreadsheet->getWorksheetIterator();
        foreach ($reader as $sheet) {
            //读取表内容
            $content = $sheet->getRowIterator();
            //逐行处理
            foreach ($content as $key => $items) {
                $rows = $items->getRowIndex();              //行
                $columns = $items->getCellIterator();       //列
                $row_arr = array();
                //确定从哪一行开始读取
                if ($rows < 2) {
                    continue;
                }
                //逐列读取
                foreach ($columns as $head => $cell) {

                    $data = $cell->getValue();

                    $row_arr[] = $data;
                }
                array_push($res_arr, array_values(array_filter($row_arr, function ($var) {
                    if ($var !== null){
                        return $var;
                    }else{
                        return "暂无数据";
                    }
                })));
            }
        }
        return $res_arr;
    }

    //处理excel
    public function dadaFilter(array $array){

        $filterData = [];
        foreach ($array as $key=>$value){
            $filterData[$key]['name'] = $value[0];
            if (!empty($value[1])){
                $place_type = PlaceType::where(['place_type_name'=>trim($value[1]),'level'=>0])->find();
                if (!is_null($place_type)){
                    $save_place_type_id = $place_type->id;
                }else{
                    $data = [
                        'place_type_name'=>$value[1],
                        'parent_id'=>0,
                        'level'=>0,
                    ];
                    $save_place_type_id = PlaceType::create($data)->id;
                }
            }else{
                $save_place_type_id = 0;
            }
            if (!empty($value[2])){
                $place_type = PlaceType::where(['place_type_name'=>trim($value[2]),'level'=>1])->find();
                if (!is_null($place_type)){
                    $save_middle_id = $place_type->id;
                }else{
                    $data = [
                        'place_type_name'=>$value[1],
                        'parent_id'=>$save_place_type_id,
                        'level'=>0,
                    ];
                    $save_middle_id = PlaceType::create($data)->id;
                }
            }else{
                $save_middle_id = 0;
            }
            if (!empty($value[3])){
                $place_type = PlaceType::where(['place_type_name'=>trim($value[3]),'level'=>2])->find();
                if (!is_null($place_type)){
                    $save_sub_class_id = $place_type->id;
                }else{
                    $data = [
                        'place_type_name'=>$value[1],
                        'parent_id'=>$save_middle_id,
                        'level'=>0,
                    ];
                    $save_sub_class_id = PlaceType::create($data)->id;
                }
            }else{
                $save_sub_class_id = 0;
            }
            $filterData[$key]['big_class'] = $save_place_type_id ?? 0;
            $filterData[$key]['middle_class'] = $save_middle_id ?? 0;
            $filterData[$key]['sub_class'] = $save_sub_class_id ?? 0;
            $filterData[$key]['longitude'] = $value[4] ?? '';
            $filterData[$key]['latitude'] = $value[5] ?? '';
            $filterData[$key]['address'] = $value[6] ?? '';
            $filterData[$key]['tel'] = $value[7] ?? '';
            $filterData[$key]['rating'] = $value[8] ?? '';
            $filterData[$key]['average_consume'] = $value[9] ?? '';
            $filterData[$key]['business'] = $value[10] ?? '';
            $filterData[$key]['remark'] = $value[11] ?? '';
            $filterData[$key]['source'] = 2;
        }
       return $filterData;
    }


    //下载excel 模板
    public function downloadExcel($file_path){
        header("Content-type:text/html;charset=utf-8");
        if(!file_exists($file_path)){
            echo "没有该文件文件";
            return ;
        }
        $fp=fopen($file_path,"r");
        $file_size=filesize($file_path);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:".$file_size);
        Header("Content-Disposition: attachment; filename=".$file_path);
        $buffer=1024;
        $file_count=0;
        //向浏览器返回数据
        while(!feof($fp) && $file_count<$file_size){
            $file_con=fread($fp,$buffer);
            $file_count+=$buffer;
            echo $file_con;
        }
        fclose($fp);

    }

}
